/**
* Project Name:sjgl
* Date:2018年12月16日
* Copyright (c) 2018, jingma All Rights Reserved.
*/

package cn.benma666.sjsj.ljq.qxgl;

import cn.benma666.constants.SysAuth;
import cn.benma666.dict.Ljpd;
import cn.benma666.domain.SysQxJsqxgl;
import cn.benma666.domain.SysQxQxxx;
import cn.benma666.exception.MyException;
import cn.benma666.iframe.DictManager;
import cn.benma666.iframe.MyParams;
import cn.benma666.iframe.PageInfo;
import cn.benma666.iframe.Result;
import cn.benma666.myutils.StringUtil;
import cn.benma666.sjsj.myutils.MyTransactional;
import cn.benma666.sjsj.web.DefaultLjq;
import cn.benma666.sjsj.web.LjqManager;
import cn.benma666.sjsj.web.UserManager;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import org.beetl.sql.core.SqlId;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 权限信息拦截器 <br/>
 * date: 2018年12月16日 <br/>
 * @author jingma
 * @version 0.1
 */
@Component
@Scope("prototype")
public class QxxxLjq extends DefaultLjq {
    /**
     * 保存授权
     */
    public Result bcsq(@org.jetbrains.annotations.NotNull MyParams myParams){
        JSONObject changeCheckData = myParams.getJSONObject("$.sys.changeCheckData");
        int count = 0;
        SysQxJsqxgl yobj = myParams.yobj(SysQxJsqxgl.class);
        for(String key:changeCheckData.keySet()){
            JSONObject node = changeCheckData.getJSONObject(key);
            if(node.getBooleanValue("checked")){
                count += LjqManager.getDb().lambdaQuery(SysQxJsqxgl.class).insertSelective(
                        SysQxJsqxgl.builder().js(yobj.getJs()).qx(node.getString("$.obj.id")).build()
                );
            }else{
                //将取消的授权改为无效
                count += LjqManager.getDb().lambdaQuery(SysQxJsqxgl.class)
                        .andEq(SysQxJsqxgl::getJs,yobj.getJs())
                        .andEq(SysQxJsqxgl::getQx,node.getString("$.obj.id"))
                        .updateSelective(
                        SysQxJsqxgl.builder().yxx(Ljpd.FALSE.getCode()).build()
                );
            }
        }
//        UserManager.flushUserQxxx();
        return success("成功修改授权信息数:"+count);
    }

    /**
     * 刷新用户权限
     */
    public Result sxyhqx(MyParams myParams) {
        //刷新用户权限信息
        UserManager.flushUserQxxx(myParams);
        return success("刷新用户权限成功！");
    }

    /**
     * 获取菜单树，完整的菜单
     */
    public Result cds(MyParams myParams){
        String[] sql = LjqManager.getSql(myParams,"cds");
        List<JSONObject> list = db(sql[0]).find(sql[1],myParams);
        return success("获取菜单成功",StringUtil.buildTree(list,"fqx","id"));
    }
    @Override
    public Result save(MyParams myParams) {
        Result r = super.save(myParams);
        SysQxQxxx yobj = myParams.yobj(SysQxQxxx.class);
        if(valByDef(yobj.getSczqx(),false)){
            if(isBlank(yobj.getSjdx())&&isBlank(myParams.obj(SysQxQxxx.class).getSjdx())){
                throw new MyException("要生成子权限，必须选择数据对象");
            }
            //新增权限且类型是连接且地址类型是数据对象则自动生成默认子权限且要求自动生成子权限
            String[] rr = LjqManager.getSql(myParams, "sczqx");
            sqlManager(rr[0]).executeUpdate(rr[1], myParams);
        }
        DictManager.clearDict("SYS_QX_QXXX");
        return r;
    }
    @Override
    @MyTransactional
    public Result update(MyParams myParams){
        SysQxQxxx obj = myParams.obj(SysQxQxxx.class);
        Result r = super.update(myParams);
        if(!r.isStatus()||obj==null){
            //批量保存场景没有自动读取数据库对象
            return swtj(r);
        }
        SysQxQxxx yobj = myParams.yobj(SysQxQxxx.class);
        String dm = yobj.getDm();
        if(StringUtil.isNotBlank(dm)&&!dm.equals(obj.getDm())){
            //权限代码调整时，联动调整子权限的代码
            getDb().update(SqlId.of("dialect.sjsj","jlgxZqx"), myParams);
        }
        return swtj(r);
    }
    @MyTransactional
    public Result fzjl(MyParams myParams){
        List<JSONObject> list = select(myParams).getData(PageInfo.class).getList(JSONObject.class);
        if(list.size()!=1){
            return failed("权限复制风险较大，一次只允许复制一个权限，系统会自动复制该权限的全部子权限："+list.size());
        }
        myParams.put(KEY_YOBJ,list.get(0));
        //复制权限
        int count = getDb().update(SqlId.of("dialect.sjsj", "qx-fzjl"), myParams);
        //更新父权限
        getDb().update(SqlId.of("dialect.sjsj", "qx-fzjl-gxfqx"), myParams);
        return success("成功复制权限："+count);
    }
    @Override
    @MyTransactional
    public Result plsc(MyParams myParams){
        //同时逻辑删除对应的子权限
        int countLj = 0;
        int countWl = 0;
        int countLjSq = 0;
        int countWlSq = 0;
        //查询出全部操作记录
        myParams.page().setTotalRequired(false);
        myParams.page().setPageSize(5000);
        boolean wlsc = myParams.sys().getWlsc();
        JSONObject treeExpandData = myParams.sys().getTreeExpandData();
        List<SysQxQxxx> list = select(myParams).getPageList(SysQxQxxx.class);
        for(SysQxQxxx obj:list){
            if(!TypeUtils.castToBoolean(obj.getMyhaschild())||treeExpandData.getBooleanValue(obj.getId())){
                //没有子权限或该节点展开跳过
                continue;
            }
            myParams.put(KEY_YOBJ,obj);
            if(!TypeUtils.castToBoolean(obj.getYxx())&& (wlsc||UserManager.hasAuth(myParams.user(), SysAuth.QTQX_SYS.name()))){
                //无效的数据且允许物理删除，删除对应的子权限
                countWl+= getDb().update(SqlId.of("dialect.sjsj","wlscZqx"), myParams);
                countWlSq+= getDb().update(SqlId.of("dialect.sjsj","wlscZqxsq"), myParams);
            }else{
                //有效数据逻辑删除子权限
                countLj+= getDb().update(SqlId.of("dialect.sjsj","ljscZqx"), myParams);
                countLjSq+= getDb().update(SqlId.of("dialect.sjsj","ljscZqxsq"), myParams);
            }
        }
        Result r = super.plsc(myParams);
        //同时逻辑删除对应的子权限
        r.addMsg("逻辑删除相关子权限"+countLj+"个，逻辑删除相关授权"+countLjSq+"个");
        if(countWl>0){
            r.addMsg("物理删除相关子权限"+countWl+"个，物理删除相关授权"+countWlSq+"个");
        }
        return swtj(r);
    }
}
